<template>
  <div class="w-full h-full p-3 rounded-xl border-slate-200 bg-white">
    <div class="flex items-center content-center mb-2">
      <div class="flex items-center bg-indigo-50/60 rounded-lg py-0.5 px-2">
        <i class="iconfont icon-shishikucunshiyitu text-indigo-500 text-base"/>
        <span class="title font-semibold text-indigo-600 ml-1.5">{{ $t('inventoryInforSummary.earlyWarning') }}</span>
      </div>
      <div class="flex-1 h-[1px] bg-gradient-to-r from-indigo-200 via-indigo-100/50 to-transparent ml-3"></div>
      <div class="px-3" style="margin-top: 5px">
        <!--  图表和切换 -->
        <el-button-group>
          <el-button type="primary" color="#626aef" plain :class="isShowLeft ? 'active-button' : 'inactive-button'"
                     size="small" @click="chartChange(1)">{{ $t('inventoryInforSummary.chart') }}
          </el-button>
          <el-button type="primary" color="#626aef" plain :class="isShowLeft ? 'inactive-button' : 'active-button'"
                     size="small" @click="chartChange(0)">{{ $t('inventoryInforSummary.details') }}
            <ArrowRight/>
          </el-button>
        </el-button-group>
      </div>
    </div>
    <div class="w-full flex items-center mt-4 overflow-hidden box-border" style="height: 92%">
      <div class="w-full h-full" v-if="isShowLeft">
        <el-empty v-if="!list.length" :description="$t('inventoryInforSummary.materialsCloseTo')"/>
        <v-chart ref="currentRef" class="chart-container" id="materialChart" v-else/>
      </div>
      <div class="table-list w-full h-full" v-else>
        <el-table
          ref="tableRef" border id="out-table" :data="headerList" :fit="true" table-layout="fixed"
          header-align="center" style="width:100%;height: 90%;" :header-cell-style="{
          color: '#1e293b',textAlign: 'center',fontWeight: '600',
          background: 'linear-gradient(to bottom, #f8fafc, #f1f5f9)',borderColor: '#e2e8f0',height: '40px'}"
          :cell-style="{textAlign: 'center',color: '#334155',borderColor: '#e2e8f0',background: '#fff',height: '40px'}">
          <el-table-column prop="barcode" :label="$t('wms.materialBarcode')">
            <template #default="scope">
              <el-tag style="padding: 5px 10px">{{ scope.row.barcode }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="materialCode" :label="$t('wms.materialCode')" width="160">
            <template #default="scope">
              <el-tag type="warning" style="padding: 5px 10px">{{ scope.row.materialCode }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="qty" :label="$t('mes.qty')">
            <template #default="scope">
              <el-tag type="success" style="padding: 5px 10px">{{ scope.row.qty }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="unit" :label="$t('wms.unit')">
            <template #default="scope">
              <el-tag type="info" style="padding: 5px 10px">{{ scope.row.unit }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="instockBatch" :label="$t('inventoryInforSummary.inboundBatch')">
            <template #default="scope">
              <el-tag effect="dark" style="padding: 5px 10px">{{ scope.row.instockBatch }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" :label="$t('wms.firstStatus')">
            <template #default="scope">
              <el-tag effect="dark" :type="scope.row.status === '已完成' ? 'success' : 'danger'"
                      class="text-xs">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <div class="flex justify-end mt-3">
          <el-pagination :current-page="data.page" :page-size="data.size"
                         :page-sizes="[10, 20, 50, 100]" small background class="custom-pagination"
                         :total="data.headerTotal" @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"/>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { onMounted, reactive, ref, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { forewarning, forewarningCharts } from '@/api/generalViewApi'
import moment from 'moment'
import useI18n from '@/hooks/language'

const { t } = useI18n()
const data = reactive({
  size: 10,
  page: 1,
  headerTotal: 0,
  detailTotal: 0,
  currentSize: 10,
  currentPage: 1
})
// 图表和明细的切换
const isShowLeft = ref(true)

const headerList = ref([])
const list = ref([])
// 图表
const currentRef = ref(null)
let autoHoverTimer = null
let currentHoverIndex = 0
let isUserInteracting = false

const renderPieOptions = () => {
  return {
    tooltip: {
      trigger: 'item',
      position: function (pos, params, dom, rect, size) {
        const tooltipWidth = size.contentSize[0]
        const tooltipHeight = size.contentSize[1]
        const containerWidth = size.viewSize[0]
        const containerHeight = size.viewSize[1]
        let x = pos[0]
        let y = pos[1]
        if (x + tooltipWidth > containerWidth) {
          x = containerWidth - tooltipWidth - 10
        }
        if (y + tooltipHeight > containerHeight) {
          y = containerHeight - tooltipHeight - 10
        }
        x = Math.max(10, x)
        y = Math.max(10, y)
        return [x, y]
      },
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e8e8e8',
      borderWidth: 1,
      padding: [12, 16],
      textStyle: {
        color: '#333',
        fontSize: 12
      },
      extraCssText: 'box-shadow: 0 2px 8px rgba(0,0,0,0.1); border-radius: 4px;',
      formatter: function (params) {
        const days = Math.abs(params.data.days)
        const statusColor = params.data.status === '已过期' ? '#ff4d4f' : '#faad14'
        const statusText = params.data.status === '已过期' ?
          `${t('common.dueDate')} ${days}${t('summary.day')} ` :
          `${t('summary.expirationDate')} ${days}${t('summary.day')} `

        return `
                        <div style="
                            background: linear-gradient(to right, ${statusColor}15, transparent);
                            padding: 12px 16px;
                            margin: -12px -16px 12px -16px;
                            border-radius: 4px 4px 0 0;
                        ">
                            <div style="
                                font-size: 14px;
                                font-weight: 600;
                                color: #333;
                                margin-bottom: 4px;
                            ">${params.name}</div>
                            <div style="
                                font-size: 12px;
                                color: ${statusColor};
                                font-weight: 500;
                            ">${statusText}</div>
                        </div>
                        <div style="
                            display: flex;
                            justify-content: space-between;
                            align-items: center;
                            padding: 8px 0;
                        ">
                            <span style="color: #666; font-size: 12px">${t('summary.materialsQty')} </span>
                            <span style="
                                font-weight: 500;
                                color: #333;
                                font-size: 13px;
                                background: #f5f5f5;
                                padding: 2px 8px;
                                border-radius: 4px;
                            ">${params.value.toLocaleString()}</span>
                        </div>
                    `
      }
    },
    legend: {
      orient: 'vertical',
      right: 20,
      top: 'center',
      data: [
        {
          name: t('common.dueDate'),
          icon: 'circle',
          textStyle: {
            color: '#ff4d4f',
            fontWeight: 'bold'
          }
        },
        {
          name: t('summary.nearexpiration'),
          icon: 'circle',
          textStyle: {
            color: '#faad14',
            fontWeight: 'bold'
          }
        },
        {
          name: t('summary.Normal'),
          icon: 'circle',
          textStyle: {
            color: '#52c41a',
            fontWeight: 'bold'
          }
        }
      ],
      formatter: function (name) {
        return name
      },
      textStyle: {
        color: '#666',
        fontSize: 12
      }
    },
    series: [
      {
        name: t('summary.MaterialStatus'),
        type: 'pie',
        radius: ['20%', '70%'],
        center: ['50%', '50%'],
        roseType: 'radius',
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2,
          color: function(params) {
            const colorMap = {
              '已过期': new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#ff4d4f' },
                { offset: 1, color: '#ff7875' }
              ]),
              '临期': new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#faad14' },
                { offset: 1, color: '#ffd666' }
              ]),
              '正常': new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#52c41a' },
                { offset: 1, color: '#95de64' }
              ])
            }
            return colorMap[params.data.status]
          }
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(13,240,248,0.6)'
          },
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        label: {
          show: true,
          formatter: function (params) {
            const days = Math.abs(params.data.days)
            const status = params.data.status === '已过期' ?
              `${t('common.dueDate')} ${days}${t('summary.day')} ` :
              `${t('summary.expirationDate')} ${days}${t('summary.day')} `

            return `{name|${params.name}}\n{value|${params.value.toLocaleString()}}\n${status}`
          },
          rich: {
            name: {
              fontSize: 14,
              lineHeight: 20,
              color: '#333',
              fontWeight: 500
            },
            value: {
              fontSize: 14,
              lineHeight: 20,
              color: '#666'
            },
            expired: {
              fontSize: 12,
              lineHeight: 20,
              color: '#ff4d4f',
              fontWeight: 500
            },
            warning: {
              fontSize: 12,
              lineHeight: 20,
              color: '#faad14',
              fontWeight: 500
            }
          }
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 10
        },
        data: list.value
      }
    ]
  }
}

// 表格
const getTable = () => {
  forewarning({
    startTime: '',
    endTime: '',
    size: data.size,
    current: data.page
  }).then(res => {
    if (res.code == 0) {
      headerList.value = res.data.records
      data.headerTotal = res.data.total
    }
  })
}

const handleSizeChange = (val) => {
  data.size = val
  getTable()
}
const handleCurrentChange = (val) => {
  data.page = val
  getTable()
}

// 获取数据并处理
const lineBar = async () => {
  await forewarningCharts({
    startTime: '',
    endTime: ''
  }).then(res => {
    if (res.code == 0) {
      list.value = []
      res.data.forEach(item => {
        const days = parseInt(item.days)
        let status = ''
        let statusClass = ''

        if (days < 0) {
          status = '已过期'
          statusClass = 'status-expired'
        } else if (days <= 30) {
          status = '临期'
          statusClass = 'status-warning'
        } else {
          status = '正常'
          statusClass = 'status-normal'
        }

        list.value.push({
          name: item.materialCode,
          value: item.qty,
          days: days,
          status: status,
          statusClass: statusClass
        })
      })
    }
  })
}

// 自动hover效果
const startAutoHover = () => {
  if (autoHoverTimer) {
    clearInterval(autoHoverTimer)
  }

  autoHoverTimer = setInterval(() => {
    if (!isUserInteracting && currentRef.value && list.value.length > 0) {
      // 先取消所有高亮
      currentRef.value.dispatchAction({
        type: 'downplay',
        seriesIndex: 0
      })

      currentHoverIndex = (currentHoverIndex + 1) % list.value.length
      // 显示tooltip
      currentRef.value.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex: currentHoverIndex
      })
      // 高亮当前项
      currentRef.value.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: currentHoverIndex
      })
    }
  }, 2000)
}

// 处理用户交互
const handleUserInteraction = () => {
  isUserInteracting = true
  if (autoHoverTimer) {
    clearInterval(autoHoverTimer)
  }

  // 用户停止交互后3秒重新开始自动hover
  setTimeout(() => {
    isUserInteracting = false
    startAutoHover()
  }, 3000)
}

// 图表和明细切换
const chartChange = async (flage) => {
  isShowLeft.value = flage ? true : false
  await getTable()
  await lineBar()
  // 清理图表
  if (currentRef.value) {
    currentRef.value.clear()
  }
  // 设置新图表选项
  if (flage && currentRef.value) {
    currentRef.value.setOption(renderPieOptions())
    // 添加图表事件监听
    currentRef.value.$el.addEventListener('mouseover', handleUserInteraction)
    currentRef.value.$el.addEventListener('mouseout', handleUserInteraction)
    startAutoHover()
  } else {
    // 如果 currentRef.value 未初始化，稍后再次尝试设置选项
    setTimeout(() => {
      if (currentRef.value) {
        currentRef.value.setOption(renderPieOptions())
        // 添加图表事件监听
        currentRef.value.$el.addEventListener('mouseover', handleUserInteraction)
        currentRef.value.$el.addEventListener('mouseout', handleUserInteraction)
        startAutoHover()
      }
    }, 100)
  }
}

onMounted(async () => {
  await getTable()
  await lineBar()
  if (currentRef.value) {
    currentRef.value.setOption(renderPieOptions())
    // 添加图表事件监听
    currentRef.value.$el.addEventListener('mouseover', handleUserInteraction)
    currentRef.value.$el.addEventListener('mouseout', handleUserInteraction)
    startAutoHover()
  } else {
    setTimeout(() => {
      if (currentRef.value) {
        currentRef.value.setOption(renderPieOptions())
        // 添加图表事件监听
        currentRef.value.$el.addEventListener('mouseover', handleUserInteraction)
        currentRef.value.$el.addEventListener('mouseout', handleUserInteraction)
        startAutoHover()
      }
    }, 100)
  }
})

onUnmounted(() => {
  if (autoHoverTimer) {
    clearInterval(autoHoverTimer)
  }
  if (currentRef.value) {
    currentRef.value.$el.removeEventListener('mouseover', handleUserInteraction)
    currentRef.value.$el.removeEventListener('mouseout', handleUserInteraction)
  }
})

</script>

<style scoped lang="scss">
/*图表*/
.chart-container {
  width: 600px;
  height: 400px;
  margin: 20px auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-radius: 12px;
  padding: 20px;
  background: white;
}

.status-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-expired {
  background: #fff1f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.status-warning {
  background: #fffbe6;
  color: #faad14;
  border: 1px solid #ffe58f;
}

.status-normal {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

/*end 图表*/
:deep(.el-form) {
  height: 18px;
  display: flex;
  justify-content: center;
}

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@keyframes blink {
  0%, 100% {
    opacity: 1; /* 完全可见 */
  }
  50% {
    opacity: 0.5; /* 半透明 */
  }
}

.active-button {
  background-color: #626aef;
  color: #ffffff;
}

.inactive-button {
  color: #626aef;
  background-color: #ffffff;
}

.dynamic-text {
  font-size: 38px;
  font-weight: bold;
  background: linear-gradient(270deg, #120101, #01350b, #162c02);
  background-size: 300% 300%;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  animation: gradient 3s ease infinite, blink 1s infinite; /* 应用渐变和闪烁动画 */
}

.card-box, .card-box2 {
  background-image: url("@/assets/images/bgcard.png");
  background-size: cover; /* 使背景图像覆盖整个元素 */
  background-position: center; /* 使背景图像居中 */
  background-repeat: no-repeat; /* 不重复背景图像 */
  padding-left: 30px;
  padding-top: 30px;
}

.card-box2 {
  transform: scaleX(-1);
  transform: scaleY(-1);
  padding-top: 26px;
}

.text-box {
  transform: scaleX(-1);
  transform: scaleY(-1);
  padding-top: 15px;
}

.table-list {
  :deep(.el-table) {
    // 表格hover效果
    tbody tr:hover > td {
      background-color: #f8fafc !important;
    }

    // 斑马纹样式
    .bg-gray-50 td {
      background-color: #f8fafc;
    }

    // 单元格过渡动画
    td {
      transition: background-color 0.2s ease;
    }

    // 表格边框
    --el-table-border-color: #e2e8f0;

    // 去除表格底部边框
    &::before {
      display: none;
    }

    //.incomplete {
    //  td {
    //    background: linear-gradient(to bottom, rgb(214, 242, 254) 0%, rgb(194, 225, 254) 100%) !important; /* 从上到下的渐变 */
    //  }
    //  // 确保鼠标悬停时也保持背景色
    //  &:hover > td {
    //    background: linear-gradient(to bottom, rgb(214, 242, 254) 0%, rgb(194, 225, 254) 100%) !important; /* 从上到下的渐变 */
    //  }
    //}
  }

  // 分页器样式优化
  :deep(.custom-pagination) {
    --el-pagination-bg-color: #fff;
    --el-pagination-hover-color: #1e293b;
    --el-pagination-button-color: #64748b;
    --el-pagination-border-radius: 4px;

    .btn-prev, .btn-next {
      background: linear-gradient(to bottom, #f8fafc, #f1f5f9);
      border: 1px solid #e2e8f0;
      color: #64748b;
      margin: 0 4px;

      &:hover:not(:disabled) {
        color: #1e293b;
        border-color: #cbd5e1;
      }

      &:disabled {
        background: #f1f5f9;
        border-color: #e2e8f0;
      }
    }

    .el-pager {
      li {
        background: linear-gradient(to bottom, #f8fafc, #f1f5f9);
        border: 1px solid #e2e8f0;
        color: #64748b;
        margin: 0 2px;
        font-weight: normal;

        &:not(.is-disabled):hover {
          color: #1e293b;
          border-color: #cbd5e1;
        }

        &.is-active {
          background: #1e293b;
          border-color: #1e293b;
          color: white;
        }
      }
    }

    .el-pagination__total {
      color: #64748b;
      margin-right: 8px;
    }
  }

  // 添加搜索框相关样式
  :deep(.search-form) {

    .el-form-item {
      margin-bottom: 0;
      margin-right: 16px;

      &:last-child {
        margin-right: 0;
      }
    }

    .el-form-item__label {
      color: #64748b;
      font-weight: normal;
    }

    .custom-input {
      .el-input__wrapper {
        background: linear-gradient(to bottom, #f8fafc, #f1f5f9);
        border: 1px solid #e2e8f0;
        box-shadow: none !important;

        &:hover {
          border-color: #cbd5e1;
        }

        &.is-focus {
          border-color: #1e293b;
        }
      }

      .el-input__inner {
        color: #1e293b;

        &::placeholder {
          color: #94a3b8;
        }
      }

      .el-input__suffix {
        color: #64748b;

        &:hover {
          color: #1e293b;
        }
      }
    }

    .custom-date-picker {
      .el-input__wrapper {
        background: linear-gradient(to bottom, #f8fafc, #f1f5f9);
        border: 1px solid #e2e8f0;
        box-shadow: none !important;

        &:hover {
          border-color: #cbd5e1;
        }

        &.is-focus {
          border-color: #1e293b;
        }
      }

      .el-input__inner {
        color: #1e293b;

        &::placeholder {
          color: #94a3b8;
        }
      }

      .el-range-separator {
        color: #64748b;
      }

      .el-input__suffix {
        color: #64748b;

        &:hover {
          color: #1e293b;
        }
      }
    }
  }
}

</style>

